import {BadRequestException, Body, Controller, Delete, Get, Inject, Post, Query, Req} from "@nestjs/common";
import {ApiBody, ApiConsumes, ApiOperation, ApiTags} from "@nestjs/swagger";
import {StaffDelDto, StaffRelateTags, StaffSaveDto} from "~/modules/consult/staff/staff.dto";
import {FastifyRequest} from "fastify";
import {plainToInstance} from "class-transformer";
import {validate} from "class-validator";
import {StaffService} from "~/modules/consult/staff/staff.service";
import {AuthUser} from "~/modules/auth/decorators/auth-user.decorator";
import {Public} from "~/modules/auth/decorators/public.decorator";

@ApiTags("Consult - 咨询师")
@Controller('consult/staff')
export class StaffController {
  @Inject()
  private readonly staffService: StaffService

  @Post()
	@Public()
  @ApiOperation({summary: '添加咨询师'})
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: StaffSaveDto})
  async addStaff(@Req() req: FastifyRequest, @AuthUser() user: IAuthUser) {
    try {
      const params: Record<string, any> = req.body

      params.file = params.file[0]

      const staffSaveDto = plainToInstance(StaffSaveDto, req.body)
      const errors = await validate(staffSaveDto)

      if (errors.length) {
        // 取出 errors[0].constraints 中的第一个错误信息，constraints为一个对象结构
        const message = Object.values(errors[0].constraints)[0]
        throw new BadRequestException(message)
      }

      // 业务逻辑
      return await this.staffService.save(staffSaveDto)
    }
    catch (error) {
      throw new BadRequestException(error?.message ?? '添加咨询师失败')
    }
  }

  @Delete()
  @ApiOperation({summary: '删除咨询师'})
  @ApiBody({type: StaffDelDto})
  async remove(@Query() query: StaffDelDto) {
    try {
      await this.staffService.remove(query.id)

      return null
    }
    catch (error) {
      throw new BadRequestException(error?.message ?? '删除咨询师失败')
    }
  }

  @Get()
	@Public()
  @ApiOperation({summary: '查询咨询师'})
  async find() {
    return await this.staffService.find()
  }

  @Post('tagRelate')
  @ApiOperation({summary: '关联咨询师标签'})
  @ApiBody({type: StaffRelateTags})
  async tagRelate(@Body() body: StaffRelateTags) {
    return await this.staffService.relate(body)
  }

	// 取消关联
	@Delete('tagRelate')
	@ApiOperation({summary: '取消关联咨询师标签'})
	@ApiBody({type: StaffRelateTags})
	async tagUnRelate(@Body() body: StaffRelateTags) {
		return await this.staffService.unRelate(body.staffId, body.tags)
	}
}
